import axios from 'axios'
import { Toast } from 'vant'
// import store from '@/store'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // if (store.getters.token) {
      // config.headers['Authorization'] = getToken();
    // }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    // if the custom code is not 200, it is judged as an error.
    /**
     * @param code 200 正常
     * @param code 0 失败
     */
    // Toast.success('成功文案')
    // Toast.fail('失败文案')
    if (res.code !== 200) {
      Toast.fail(res.msg)
      

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 401 || res.code === 50012 || res.code === 50014) {
        // to re-login
        Toast.fail(res.msg)
          // store.dispatch('user/resetToken').then(() => {
          //   location.reload()
          // })
        // MessageBox.confirm(
        //   '您已经登出或Token失效，请重新登录',
        //   '提示',
        //   {
        //     confirmButtonText: '重新登录',
        //     // cancelButtonText: '退出',
        //     type: 'warning'
        //   }
        // ).then(() => {
        //   store.dispatch('user/resetToken').then(() => {
        //     location.reload();
        //   });
        // });
      }
      return Promise.reject(new Error(res.msg || '请求失败'));
    } else {
      return res.result
    }
  },
  error => {
    console.log('err' + error) // for debug
      Toast.fail(error.message)
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.reject(error)
  }
)

export default service
